package com.zaizai.controller;

import com.zaizai.aop.AutoLog;
import com.zaizai.domain.AjaxResult;
import com.zaizai.domain.Commodity;
import com.zaizai.domain.dto.BatchUpdateRequest;
import com.zaizai.service.ICommodityService;
import com.zaizai.utils.ServletUtils;
import org.springframework.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import com.github.pagehelper.PageHelper;

import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.stream.Collectors;

import static com.zaizai.domain.AjaxResult.success;
import static com.zaizai.domain.AjaxResult.error;

/**
 * 商品详情Controller
 *
 * @author zaiZai
 * @date 2024-10-21
 */
@RestController
@RequestMapping("/commodity")
public class CommodityController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(CommodityController.class);

    @Autowired
    private WebRequest webRequest;

    @Autowired
    private ICommodityService commodityService;

    /**
     * 查询商品详情列表
     */
    @GetMapping("/list")
    public AjaxResult list(Commodity commodity) {
        try {
            // 从请求参数中获取 ids
            String ids = webRequest.getParameter("idsStr");
            if (ids != null && !ids.isEmpty()) {
                List<Long> idList = Arrays.stream(ids.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
                commodity.setIdList(idList);
                if (ServletUtils.getParameterToInt("pageNum") != null) {
                    Integer pageNum = ServletUtils.getParameterToInt("pageNum");
                    PageHelper.startPage(pageNum, idList.size());
                }
            }

            // 如果没有传入分页参数，则返回所有数据
            if (ServletUtils.getParameterToInt("pageNum") == null) {
                List<Commodity> list = commodityService.selectAllCommodities();
                return success(list);
            }

            // 如果不是按ID列表查询，使用常规分页
            if (commodity.getIdList() == null || commodity.getIdList().isEmpty()) {
                startPage();
            }
            List<Commodity> list = commodityService.selectCommodityList(commodity);
            return success(getDataTable(list));
        } catch (Exception e) {
            log.error("Error getting commodity list:", e);
            return error("获取商品列表失败");
        }
    }

    /**
     * 获取商品详情详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(commodityService.selectCommodityById(id));
    }

    /**
     * 新增商品详情
     */
    @PostMapping
    @AutoLog("新增商品信息")
    public AjaxResult add(@RequestBody Commodity commodity) {
        return success(commodityService.insertCommodity(commodity));
    }

    /**
     * 修改商品详情
     */
    @PutMapping
    @AutoLog("修改商品信息")
    public AjaxResult edit(@RequestBody Commodity commodity) {
        log.info("Updating commodity: {}", commodity);
        try {
            return success(commodityService.updateCommodity(commodity));
        } catch (Exception e) {
            log.error("Error updating commodity:", e);
            throw e;
        }
    }

    /**
     * 删除商品详情
     */
    @DeleteMapping("/{ids}")
    @AutoLog("删除商品信息")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return success(commodityService.deleteCommodityByIds(ids));
    }

    /**
     * 获取商品历史价格
     */
    @GetMapping("/history-prices/{id}")
    public AjaxResult getHistoryPrices(@PathVariable("id") Long id) {
        try {
            List<Map<String, Object>> prices = commodityService.getHistoryPrices(id);
            return success(prices);
        } catch (Exception e) {
            log.error("Error getting history prices for commodity {}: ", id, e);
            return error("获取历史价格失败");
        }
    }

    /**
     * 获取热销商品 TOP 10
     */
    @GetMapping("/top-selling")
    public AjaxResult getTopSellingProducts() {
        try {
            List<Map<String, Object>> topProducts = commodityService.getTopSellingProducts();
            return success(topProducts);
        } catch (Exception e) {
            log.error("Error getting top selling products:", e);
            return error("获取热销商品失败");
        }
    }

    @GetMapping("/listAll")
    public AjaxResult listAll() {
        try {
            List<Commodity> list = commodityService.selectAllCommodities();
            log.info("查询到所有商品数量: {}", list.size());
            return AjaxResult.success(list);
        } catch (Exception e) {
            log.error("Error getting all products:", e);
            return error("获取商品列表失败");
        }
    }

    @PostMapping("/batch-update")
    public AjaxResult batchUpdate(@RequestBody BatchUpdateRequest request) {
        try {
            commodityService.batchUpdate(request.getOperations());
            return success();
        } catch (Exception e) {
            log.error("批量更新失败:", e);
            return error(e.getMessage());
        }
    }
}
